//
//  NetworkTools.swift
//  练习-04-Swift AFN
//
//  Created by teacher on 16/2/24.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

/// 网络请求枚举类型，Swift中的枚举可以指定不同的数据类型
enum CZRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    let appkey = "978609048"
    let appSecret = "548b731599e198352c2f9a9b7cb24c6c"
    let redirectUri = "http://www.baidu.com"
  
    
    /// 单例
    static let sharedTools: NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tools
    }()
    
    /// 封装 AFN 方法发起网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调(json字典)
    func request(method: CZRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: [String: AnyObject]?)->()) {
        
        // 回调方法的参数，可以从 AFN 的方法直接粘贴
        // 成功回调
        let success = { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            
            if let result = responseObject as? [String: AnyObject] {
                finished(result: result)
            } else {
                
                print("数据格式错误")
                finished(result: nil)
            }
        }
        // 失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            print("网络请求错误 \(error)")
            finished(result: nil)
        }
        
        if method == .GET {
            // GET 请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            // POST 请求
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}

